package com.file.system.plugin.error;

import com.file.system.entity.res.BaseCode;
import com.file.system.entity.res.CommonResult;
import org.springframework.boot.web.servlet.error.ErrorController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 异常
 *
 * @author jch
 */
@RestController
public class MyError implements ErrorController {

    /**
     * 获取请求中的状态码
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @RequestMapping("/error")
    public CommonResult handleError(HttpServletRequest request, HttpServletResponse response) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        //根据状态码返回不同的结果
        switch (statusCode) {
            case 500:
                return CommonResult.fail(BaseCode.Common.SYSTEM_500);
            case 404:
                return CommonResult.fail(BaseCode.Common.SYSTEM_404);
            case 403:
                return CommonResult.fail(BaseCode.Common.SYSTEM_403);
            default:
                return CommonResult.fail(BaseCode.Common.SYSTEM_500);
        }
    }

    /**
     * 没有权限
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @GetMapping("/not/auth")
    public CommonResult notAuth() {
        //返回未授权的CommonResult
        return CommonResult.fail(BaseCode.Common.USER_NOT_AUTH);
    }

    /**
     * 登录过期
     *
     * @return CommonResult
     * @apiNote -
     * @author jch
     */
    @GetMapping("/not/login")
    public CommonResult notLogin() {
        //返回未登录的CommonResult
        return CommonResult.fail(BaseCode.Common.USER_TIME_OUT);
    }

    public String getErrorPath() {
        return "/error";
    }
}

